package com.xz.hlx11;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HuluxiaApi {
    private static final String TAG = "HuluxiaApi";
    private static final Handler handler = new Handler(Looper.getMainLooper());
    
    // 请求节流相关变量
    private static long lastLotteryRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 1000; // 最小请求间隔2秒
    
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .followRedirects(true)
            .followSslRedirects(true)
            .build();

    public interface LoginCallback {
        void onSuccess(String userId, String key);
        void onError(String error);
    }

    public interface LotteryCallback {
        void onResult(String result);
        void onError(String error);
    }

    public interface KeyCheckCallback {
        void onValid(boolean isValid);
        void onError(String error);
    }

    public interface HuluNumberCallback {
        void onSuccess(int huluCount);
        void onError(String error);
    }

    // MD5加密
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 生成随机字符串
    public static String generateNonceStr(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder nonceStr = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            nonceStr.append(chars.charAt(random.nextInt(chars.length())));
        }
        return nonceStr.toString();
    }

    // 登录方法
    public static void login(String username, String password, boolean isHuluxia, LoginCallback callback) {
        String web = isHuluxia ? "tool_web" : "floor_web";
        String mdPassword = md5(password);
        String sign = "account" + username + "device_code[d]b305cc73-8db8-4a25-886f-e73c502b1e99password" + mdPassword + "voice_codefa1c28a5b62e79c3e63d9030b6142e4b";
        sign = md5(sign);

        String url = "http://floor.huluxia.com/account/login/ANDROID/4.1.8?platform=2&gkey=000000&app_version=4.3.0.4&versioncode=20141495&market_id=" + web + "&_key=&device_code=%5Bd%5Db305cc73-8db8-4a25-886f-e73c502b1e99&phone_brand_type=UN";

        FormBody formBody = new FormBody.Builder()
                .add("account", username)
                .add("login_type", "2")
                .add("password", mdPassword)
                .add("sign", sign)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("User-Agent", "okhttp/3.8.1")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Login failed", e);
                callback.onError("网络错误: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    Log.d(TAG, "Login response: " + responseBody);
                    try {
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
                        if (jsonObject.has("user") && jsonObject.has("_key")) {
                            JsonObject user = jsonObject.getAsJsonObject("user");
                            String userId = user.get("userID").getAsString();
                            String key = jsonObject.get("_key").getAsString();
                            callback.onSuccess(userId, key);
                        } else {
                            String msg = jsonObject.has("msg") ? jsonObject.get("msg").getAsString() : "登录失败";
                            callback.onError(msg);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Parse login response failed", e);
                        callback.onError("解析登录响应失败");
                    }
                } else {
                    callback.onError("登录请求失败: " + response.code());
                }
            }
        });
    }

    // 检查Key是否有效
    public static void checkKey(String key, KeyCheckCallback callback) {
        Log.d(TAG, "检查Key有效性，Key长度: " + key.length());
        String url = "http://floor.huluxia.com/account/security/info/ANDROID/4.2.2?_key=" + key;
        Log.d(TAG, "请求URL: " + url);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Check key failed", e);
                callback.onError("网络错误: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "Key检查响应码: " + response.code());
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    Log.d(TAG, "Key检查响应内容: " + responseBody);
                    try {
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
                        
                        // 记录所有可用字段
                        StringBuilder availableFields = new StringBuilder("可用字段: ");
                        for (String fieldKey : jsonObject.keySet()) {
                            availableFields.append(fieldKey).append(", ");
                        }
                        Log.d(TAG, availableFields.toString());
                        
                        boolean status = jsonObject.has("status") && jsonObject.get("status").getAsBoolean();
                        Log.d(TAG, "Key验证结果 status字段: " + status);
                        callback.onValid(status);
                    } catch (Exception e) {
                        Log.e(TAG, "Parse check key response failed", e);
                        callback.onError("解析响应失败: " + e.getMessage());
                    }
                } else {
                    Log.e(TAG, "Key检查请求失败，响应码: " + response.code());
                    callback.onError("检查Key失败: " + response.code());
                }
            }
        });
    }



// 检查葫芦数量
    public static void checkHL(String key, String userId, HuluNumberCallback callback) {
        String url = "http://floor.huluxia.com/user/info/ANDROID/4.1.8?platform=2&gkey=000000&app_version=4.2.1.8.2&versioncode=377&market_id=tool_web&_key=" + key + "&device_code=%5Bd%5D46680efe-4704-4c34-ac9e-b7f8c60b088a&phone_brand_type=UN&user_id=" + userId;

        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; M2007J3SC Build/SKQ1.211006.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 Mobile Safari/537.36")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Connection", "keep-alive")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Check hulu count failed", e);
                callback.onError("网络错误: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody;
                    try {
                        // 使用更安全的方式读取响应
                        if (response.body() != null) {
                            byte[] bytes = response.body().bytes();
                            responseBody = new String(bytes, "UTF-8");
                        } else {
                            callback.onError("响应体为空");
                            return;
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to read response body", e);
                        callback.onError("读取响应失败: " + e.getMessage());
                        return;
                    }
                    
                    Log.d(TAG, "Check hulu response length: " + responseBody.length());
                    Log.d(TAG, "Check hulu response preview: " + responseBody.substring(0, Math.min(200, responseBody.length())));
                    
                    try {
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
                        
                        // 记录完整响应以便调试
                        Log.d(TAG, "Full response: " + responseBody);
                        
                        // 尝试检查是否有其他可能的字段结构
                        StringBuilder availableFields = new StringBuilder("Available fields: ");
                        for (String key : jsonObject.keySet()) {
                            availableFields.append(key).append(", ");
                        }
                        Log.d(TAG, availableFields.toString());
                        
                        // 根据您提供的API响应结构，直接从根对象获取 credits 字段
                        if (jsonObject.has("credits")) {
                            int huluCount = jsonObject.get("credits").getAsInt();
                            Log.d(TAG, "Found credits: " + huluCount);
                            callback.onSuccess(huluCount);
                            return;
                        }
                        
                        
                        callback.onError("未找到葫芦数量信息 - 可用字段: " + availableFields.toString());
                    } catch (Exception e) {
                        Log.e(TAG, "Parse hulu count response failed", e);
                        callback.onError("解析葫芦数量失败: " + e.getMessage());
                    }
                } else {
                    callback.onError("检查葫芦数量失败: " + response.code());
                }
            }
        });
    }



    // 抽奖方法
    public static void lottery(String userId, String key, int frequency, int currentHuluCount, int threshold, LotteryCallback callback) {
        // 检查阈值
        if (currentHuluCount <= threshold) {
            callback.onError("达到停止阈值(" + threshold + ")，停止抽奖");
            return;
        }

        performLottery(userId, key, frequency, callback);
    }
    
    // 实际执行抽奖的方法
    private static void performLottery(String userId, String key, int frequency, LotteryCallback callback) {
        // 直接执行抽奖请求，延迟由LotteryActivity控制
        executeLotteryRequest(userId, key, frequency, callback);
    }
    
    // 执行抽奖请求的方法
    private static void executeLotteryRequest(String userId, String key, int frequency, LotteryCallback callback) {
        // 检查请求频率限制
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastLotteryRequestTime < MIN_REQUEST_INTERVAL) {
            Log.w(TAG, "请求频率过快，跳过本次抽奖请求");
            callback.onError("请求频率限制，请稍后再试");
            return;
        }
        lastLotteryRequestTime = currentTime;
        
        String url = "https://huodong.huluxia.com/api/view/activity/eleventhAnniversary/lottery";
        
        long currentTimestamp = System.currentTimeMillis() / 1000;
        String nonceStr = generateNonceStr(16);
        String signData = "_key" + key + "deviceCode[d]272188e5-dc54-44c1-adc3-b04b204ddc8cfrequency" + frequency + "nonceStr" + nonceStr + "timestamp" + currentTimestamp + "ec6d94ff2f5e2b31382c23d3bdace5e9";
        String sign = md5(signData);

        FormBody formBody = new FormBody.Builder()
                .add("_key", key)
                .add("deviceCode", "[d]272188e5-dc54-44c1-adc3-b04b204ddc8c")
                .add("timestamp", String.valueOf(currentTimestamp))
                .add("nonceStr", nonceStr)
                .add("frequency", String.valueOf(frequency))
                .add("sign", sign)
                .build();

        String referer = "https://huodong.huluxia.com/hlx-eleventh-anniversary/?versionCode=20141512&market_id=floor_web&userId=" + userId + "&extraInfo=&device_code=%5Bw%5D02%3A00%3A00%3A00%3A00%3A00-%5Bi%5D863342023205943-%5Bs%5D89860052445246571934&_key=" + key;

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("Host", "huodong.huluxia.com")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; M2007J3SC Build/SKQ1.211006.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 MQQBrowser/6.2 TBS/046291 Mobile Safari/537.36")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Origin", "https://huodong.huluxia.com")
                .addHeader("X-Requested-With", "com.huluxia.gametools")
                .addHeader("Sec-Fetch-Site", "same-origin")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Referer", referer)
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Lottery failed", e);
                callback.onError("网络错误: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 尝试多种编码方式读取响应
                    String responseBody = null;
                    
                    try {
                        // 首先尝试让OkHttp自动处理编码（包括gzip解压缩）
                        responseBody = response.body().string();
                        Log.d(TAG, "Lottery response (auto encoding): " + responseBody);
                    } catch (Exception e) {
                        Log.e(TAG, "Auto encoding failed, trying manual", e);
                        try {
                            // 如果自动编码失败，尝试手动处理
                            byte[] responseBytes = response.body().bytes();
                            
                            // 尝试不同的编码
                            String[] encodings = {"UTF-8", "GBK", "GB2312", "ISO-8859-1"};
                            for (String encoding : encodings) {
                                try {
                                    String testResponse = new String(responseBytes, encoding);
                                    // 检查是否包含中文字符且没有乱码
                                    if (!testResponse.contains("�") && (testResponse.contains("成功") || testResponse.contains("失败") || testResponse.contains("奖励") || testResponse.contains("{"))) {
                                        responseBody = testResponse;
                                        Log.d(TAG, "Successfully decoded with " + encoding);
                                        break;
                                    }
                                } catch (Exception ex) {
                                    Log.d(TAG, "Failed to decode with " + encoding);
                                }
                            }
                            
                            // 如果所有编码都失败，使用UTF-8作为默认
                            if (responseBody == null || responseBody.contains("�")) {
                                responseBody = new String(responseBytes, "UTF-8");
                            }
                        } catch (Exception ex) {
                            Log.e(TAG, "Manual encoding also failed", ex);
                            responseBody = "编码解析失败";
                        }
                    }
                    
                    
                    // 尝试解析JSON响应并提取可读信息
                    try {
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
                        
                        // 构建格式化的结果信息
                        StringBuilder resultBuilder = new StringBuilder();
                        
                        if (jsonObject.has("result")) {
                            JsonObject result = jsonObject.getAsJsonObject("result");
                            
                            if (result.has("records") && result.get("records").isJsonArray()) {
                                result.getAsJsonArray("records").forEach(record -> {
                                    JsonObject recordObj = record.getAsJsonObject();
                                    if (recordObj.has("boxName")) {
                                        String boxName = recordObj.get("boxName").getAsString();
                                        resultBuilder.append("宝箱: ").append(boxName).append("\n");
                                    }
                                    if (recordObj.has("awardName")) {
                                        String awardName = recordObj.get("awardName").getAsString();
                                        resultBuilder.append("奖励: ").append(awardName).append("\n");
                                    }
                                    resultBuilder.append("---\n");
                                });
                            }
                            
                            if (result.has("msg")) {
                                String msg = result.get("msg").getAsString();
                                resultBuilder.append("消息: ").append(msg).append("\n");
                            }
                            
                            if (result.has("status")) {
                                boolean status = result.get("status").getAsBoolean();
                                resultBuilder.append("状态: ").append(status ? "成功" : "失败").append("\n");
                            }
                        }
                        
                        // 如果解析成功，返回格式化的结果
                        String formattedResult = resultBuilder.toString().trim();
                        if (!formattedResult.isEmpty()) {
                            callback.onResult(formattedResult);
                        } else {
                            // 如果没有解析到有用信息，返回原始响应（但更简洁）
                            callback.onResult("抽奖完成，但未获得详细信息");
                        }
                        
                    } catch (Exception e) {
                        Log.e(TAG, "Parse lottery response failed", e);
                        // JSON解析失败，返回简化的原始响应
                        callback.onResult("抽奖请求已发送，服务器响应格式异常");
                    }
                } else {
                    callback.onError("抽奖请求失败: " + response.code());
                }
            }
        });
    }
}
